package com.health.viewscontrols.medical.device.bp;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.health.httpbean.model.BpModel;
import com.health.tablebean.BTDevice;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.inuker.bluetooth.library.Contast;
import com.inuker.bluetooth.library.ZBleManager;
import com.inuker.bluetooth.library.interFace.IBleConnectStatusListener;
import com.inuker.bluetooth.library.interFace.IBleIndicateListener;
import com.inuker.bluetooth.library.interFace.IBleWriteListener;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.nova.health.ble.callback.OnDeviceConnectChangedListener;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.services.BluetoothConstant;
import com.novabluetooth.views.BlueToothConstant;
import com.novabluetooth.views.twj.TwjConstans;
import com.novabluetooth.views.twj.ZHexUtil;

import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 爱奥乐血压计4.0
 */
public class BPAALActivity extends BaseDeviceActivity {

    private ZBleManager mBleManager;
    private String mHighValue, mmLowValue, mHeratValue;
    byte[] data_temp = new byte[]{};
    int length = 8;

    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.bp_aal);

        mBleManager = ZBleManager.getInstance();
        mBleManager.initBle(this);

        BleManager.getInstance().init(getApplication());

        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setDeviceMac(deviceEnum.getMac())
                .setScanTimeOut(10000)              // 扫描超时时间，可选，默认10秒；小于等于0表示不限制扫描时间
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);

    }


    @Override
    public void startDevice() {

        showProgressDialog("开始连接设备");
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
            }

            @Override
            public void onLeScan(BleDevice bleDevice) {
                super.onLeScan(bleDevice);
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                if (bleDevice != null && bleDevice.getMac() != null && deviceEnum.getMac().equals(bleDevice.getMac())) {
                    connDevice();
                }
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {

            }
        });
    }

    @Override
    public void update(String hexString) {

    }

    private void saveMaiboboData(String bloodUp, String bloodDown, String heart) {
        try {
//            disconnectDevice();
            cancelProgressDialog();
            //收缩压、舒张压、心率
            String results = DeviceShowSaveData.getDataShow(bloodUp + ";" + bloodDown + ";" + heart + ";",
                    BluetoothConstant.XUEYA_YE680A_YUYUE);

            BpModel bpModel = new BpModel();
            bpModel.setHighpressure(bloodUp + "");
            bpModel.setLowvoltage(bloodDown + "");
            bpModel.setPulse(heart + "");
            DeviceShowSaveData.saveXueya(GsonUtils.toJson(bpModel));

            cancelProgressDialog();
            ZBleManager.getInstance().disConnectDevice(deviceEnum.getMac());
            ZBleManager.getInstance().destroy(deviceEnum.getMac());
            tv_result.setText("测量结果：\n        " + results);
            tv_state.setText("获取测量结果成功");
        } catch (Exception e) {
            Log.e(TAG, "报异常了: " + e.toString());
        }
    }

    @Override
    public void disconnectDevice() {
        try {
            ZBleManager.getInstance().disConnectDevice(deviceEnum.getMac());
            ZBleManager.getInstance().destroy(deviceEnum.getMac());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void connDevice() {

        mBleManager.connect(deviceEnum.getMac(), new IBleConnectStatusListener() {
            @Override
            public void onStartConnect() {
                blueToothState.setText("开始连接蓝牙");
            }

            @Override
            public void onConnectFail() {
                blueToothState.setText("连接蓝牙失败");
            }

            @Override
            public void onConnectSuccess(int code, BleGattProfile data, String mac) {
                blueToothState.setText("连接蓝牙成功");
                showProgressDialog("等待接收血压数据");
                indicate();
            }

            @Override
            public void onDisConnected(String mac) {
                blueToothState.setText("蓝牙连接已取消");
            }
        });
    }

    @SuppressLint("CheckResult")
    private void write(final String mac, final byte[] data) {
        mBleManager.write(mac, Contast.GATT_SERVICE_PRIMARY,
                Contast.CHARACTERISTIC_WRITEABLE, data, new IBleWriteListener() {
                    @Override
                    public void onWriteSuccess() {
                        Log.e(TAG, "onWriteSuccess: " +  Arrays.toString(data));
                    }

                    @Override
                    public void onWriteFailure(int code) {
                        Log.e(TAG, "onWriteFailure: " +  Arrays.toString(data));
                    }
                });
    }

    private void indicate() {
        mBleManager.indicate(deviceEnum.getMac(), Contast.GATT_SERVICE_PRIMARY,
                Contast.CHARACTERISTIC_READABLE, new IBleIndicateListener() {
                    @Override
                    public void onIndicateSuccess() {
                        try {
                            Thread.sleep(500L);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        byte[] data_00 = ZHexUtil.hexStringToBytes(TwjConstans.getSendHex(1));
                        write(deviceEnum.getMac(), data_00);
                    }

                    @Override
                    public void onIndicateFailure(int code) {
                        Log.e(TAG, "onIndicateFailure: " + code );
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        Log.e(TAG, "血压计返回: " + Arrays.toString(data) );
                        //解析非信息包
                        if (data.length != 15 && data.length != 18)
                            getValueData2(data);
                    }
                });
    }

    private byte[] byteMerger(byte[] byte_1, byte[] byte_2) {
        byte[] byte_3 = new byte[byte_1.length + byte_2.length];
        System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
        System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
        return byte_3;
    }

    /**
     * 得到过程包显示出来
     */
    private void setPreValue(byte[] data) {
        byte[] valueArr = {data[6], data[5]};
        try {
            String strValue = String.valueOf(Integer.valueOf(ZHexUtil.encodeHexStr(valueArr), 16));//血压 6+5 在转换成10进制
            tv_result.setText("实时数据: " + strValue + " /mmHg");
            Log.e(TAG, "得到过程包显示出来: " +  strValue);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void getValueData2(byte[] data) {
        if (null == data) return;

        //先判断是过程包还是结果包
        if (data_temp.length < 3) {
            data_temp = byteMerger(data_temp, data);
            if (data_temp.length > 2) {
                byte index2 = data_temp[2];
                //[85, 5, -18, 1, 75]
                switch (index2) {
                    case 2:
                        length = 8;
                        break;
                    case 3:
                        length = 14;
                        break;
                    case -18:
                        length = 5;
                        break;
                }
                //如果加起来长度刚好够了，
                if (data_temp.length == length) {
                    switch (length) {
                        case 8:
                            //过程包
                            setPreValue(data_temp);
                            break;
                        case 14:
                            //结果包
                            try {
                                byte[] valueArr = {data_temp[10], data_temp[9]};
                                String strValue = ZHexUtil.encodeHexStr(valueArr);//血糖 10+9 在转换成10进制
                                mHighValue = String.valueOf(Integer.valueOf(strValue, 16));//高压
                                mmLowValue = String.valueOf(Integer.valueOf(ZHexUtil.encodeHexStr(new byte[]{data_temp[11]}), 16));//低压
                                mHeratValue = String.valueOf(Integer.valueOf(ZHexUtil.encodeHexStr(new byte[]{data_temp[12]}), 16));//低压
                                saveMaiboboData(mHighValue, mmLowValue, mHeratValue);
                                Log.e(TAG, "getValueData2:结果包 " +  mHighValue + "  mmLowValue:" + mmLowValue + " mHeratValue:" + mHeratValue);
                            } catch (Exception e) {
                                Log.e("zdw007", e.toString());
                            }
                            break;
                        case 5:
                            break;
                    }
                    data_temp = null;
                    data_temp = new byte[]{};
                }
            }
        } else {
            if (data_temp.length < length) {
                //如果加起来长度还是不够，就直接拼接
                if (data_temp.length + data.length < length) {
                    data_temp = byteMerger(data_temp, data);
                }
                //如果加起来长度刚好够了，
                else if (data_temp.length + data.length == length) {
                    data_temp = byteMerger(data_temp, data);
                    Log.e("zdw007", "length：" + length + "data_temp：" + Arrays.toString(data_temp));
                    switch (length) {
                        case 8:
                            setPreValue(data_temp);
                            break;
                        case 14:
                            try {
                                byte[] valueArr = {data_temp[10], data_temp[9]};
                                String strValue = ZHexUtil.encodeHexStr(valueArr);//血糖 10+9 在转换成10进制
                                mHighValue = String.valueOf(Integer.valueOf(strValue, 16));//高压
                                mmLowValue = String.valueOf(Integer.valueOf(ZHexUtil.encodeHexStr(new byte[]{data_temp[11]}), 16));//低压
                                mHeratValue = String.valueOf(Integer.valueOf(ZHexUtil.encodeHexStr(new byte[]{data_temp[12]}), 16));//低压
                                Log.e(TAG, "case 14   " +  mHighValue + "  mmLowValue:" + mmLowValue + " mHeratValue:" + mHeratValue);
                            } catch (Exception e) {
                                Log.e("zdw007", e.toString());
                            }
                            break;
                        case 5:
                            ToastUtils.showShort("血压测量出错，测量中请保持坐姿、手势平稳，勿动");
                            break;

                    }
                    data_temp = null;
                    data_temp = new byte[]{};
                }
                //如果加起来长度超了，截取下来
                else {
                    int excess_length = data_temp.length + data.length - length;
                    data_temp = byteMerger(data_temp, subBytes(data, 0, data.length - excess_length));
                    setPreValue(data_temp);
                    data_temp = subBytes(data, data.length - excess_length, excess_length);
                }
            } else if (data_temp.length == length) {
                switch (length) {
                    case 8:
                        setPreValue(data_temp);
                        break;
                    case 14:
                        try {
                            byte[] valueArr = {data_temp[10], data_temp[9]};
                            String strValue = ZHexUtil.encodeHexStr(valueArr);//血糖 10+9 在转换成10进制
                            mHighValue = String.valueOf(Integer.valueOf(strValue, 16));//高压
                            mmLowValue = String.valueOf(Integer.valueOf(ZHexUtil.encodeHexStr(new byte[]{data_temp[11]}), 16));//低压
                            mHeratValue = String.valueOf(Integer.valueOf(ZHexUtil.encodeHexStr(new byte[]{data_temp[12]}), 16));//低压
                            Log.e(TAG, "case 141414   " +  mHighValue + "  mmLowValue:" + mmLowValue + " mHeratValue:" + mHeratValue);
                        } catch (Exception e) {
                            Log.e("zdw007", e.toString());
                        }
                        break;
                    case 5:
                        ToastUtils.showShort("血压测量出错，测量中请保持坐姿、手势平稳，勿动");
                        break;

                }
                data_temp = null;
                data_temp = new byte[]{};
            }
        }
    }

    /**
     * 在字节数组中截取指定长度数组
     */
    public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        System.arraycopy(src, begin, bs, 0, count);
        return bs;
    }

}
